<template>
  <div class="auto-refresh-tips">
    <template v-if="refreshStatus === 0">
      <span class="refresh-tips">
        <i class="el-icon-loading"></i>
        <span class="tips">数据更新中</span>
      </span>
    </template>
    <template v-else>
      <el-tooltip effect="dark" content="点击将立即刷新" placement="top">
        <span class="refresh-tips" @click="onRrefresh">
          <slot></slot>
          <template v-if="!$slots.default">
            <i class="el-icon-success"></i>
            <span class="tips refresh-btn">数据已更新</span>
          </template>
          <span v-if="autoRefresh">（每隔{{ duration / 1000 }}秒将自动刷新）</span>
        </span>
      </el-tooltip>
    </template>
  </div>
</template>

<script>
export default {
  name: 'AutoRefreshTips',
  components: {},
  props: {
    duration: {
      type: Number,
      default: 10000,
    },
  },
  data() {
    return {
      refreshStatus: 1,
      refreshTimer: null,
      autoRefresh: true,
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {
    this.startRefreshTimer()
  },
  methods: {
    onRrefresh() {
      this.refreshStatus = 0
      this.$emit('refresh', refreshAgain => {
        // 延时展示更新状态，否则loading太快
        setTimeout(() => {
          this.refreshStatus = 1
          this.autoRefresh = refreshAgain
          this.autoRefresh && this.startRefreshTimer()
        }, 400)
      })
    },
    startRefreshTimer() {
      this.stopRefreshTimer()
      this.refreshTimer = setTimeout(() => {
        this.onRrefresh()
      }, this.duration)
    },
    stopRefreshTimer() {
      if (this.refreshTimer) {
        clearTimeout(this.refreshTimer)
        this.refreshTimer = null
      }
    },
  },
  beforeDestroy() {
    this.stopRefreshTimer()
  },
}
</script>
<style lang="scss" scoped>
.auto-refresh-tips {
  .refresh-tips {
    font-size: 14px;
    margin-left: 20px;
    color: #666;
    i {
      margin-right: 5px;
    }
    .el-icon-success {
      color: #67c23a;
    }
  }
  .refresh-btn {
    cursor: pointer;
    &:hover {
      color: #333;
    }
  }
}
</style>
